package com.chc.web.live_user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chc.utils.Msg;
import com.chc.web.fee_park.entity.FeePark;
import com.chc.web.fee_park.mapper.FeeParkMapper;
import com.chc.web.fee_park.service.FeeParkService;
import com.chc.web.fee_power.entity.FeePower;
import com.chc.web.fee_power.service.FeePowerService;
import com.chc.web.fee_water.entity.FeeWater;
import com.chc.web.fee_water.service.FeeWaterService;
import com.chc.web.live_house.entity.LiveHouse;
import com.chc.web.live_house.service.LiveHouseService;
import com.chc.web.live_park.entity.LivePark;
import com.chc.web.live_park.mapper.LiveParkMapper;
import com.chc.web.live_role.entity.LiveRole;
import com.chc.web.live_role.service.LiveRoleService;
import com.chc.web.live_user.entity.AssignHouseParm;
import com.chc.web.live_user.entity.LiveUser;
import com.chc.web.live_user.entity.LiveUserParm;
import com.chc.web.live_user.service.LiveUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2022/01/15/10:55
 * @Description: 业主控制器
 */

@RestController
@RequestMapping("/api/liveUser")
public class LiveUserController {

    @Autowired
    private LiveUserService liveUserService;

    @Autowired
    private FeeWaterService feeWaterService;

    @Autowired
    private FeePowerService feePowerService;

    @Autowired
    private LiveRoleService liveRoleService;

    @Autowired
    private FeeParkService feeParkService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private LiveHouseService liveHouseService;

    @Resource
    private LiveParkMapper liveParkMapper;
    /**
     * 业主列表查询
     * */
    @GetMapping("/list")
    public Msg getList(LiveUserParm liveUserParm){
        //构造分页对象
        IPage<LiveUser> page = new Page<>();
        page.setSize(liveUserParm.getPageSize());
        page.setCurrent(liveUserParm.getCurrentPage());
        IPage<LiveUser> list = liveUserService.getList(page, liveUserParm.getLoginName(), liveUserParm.getPhone());
        return Msg.success("查询成功",list);
    }

    /**
     * 新增业主
     * */
    @PostMapping
    @PreAuthorize("hasAuthority('sys:liveUser:add')")
    public Msg add(@RequestBody LiveUser liveUser) {
        //查询用户名是否被占用
        QueryWrapper<LiveUser> query = new QueryWrapper();
        query.lambda().eq(LiveUser::getUsername, liveUser.getUsername());
        LiveUser one = liveUserService.getOne(query);
        if (one != null) {
            return Msg.error("帐户已被占用!");
        }
            liveUser.setPassword(passwordEncoder.encode(liveUser.getPassword()));
            liveUserService.saveLiveUser(liveUser);
            return Msg.success("新增业主成功");

        //用户密码需要加密
//        liveUser.setPassword(DigestUtils.md5DigestAsHex(liveUser.getPassword().getBytes()));
    }

    /**
     * 编辑业主
     * */
    @PutMapping
    @PreAuthorize("hasAuthority('sys:liveUser:edit')")
    public Msg edit(@RequestBody LiveUser liveUser){
        //编辑判断登录名是否被使用
        //查询用户名是否被占用
        QueryWrapper<LiveUser> query = new QueryWrapper();
        query.lambda().eq(LiveUser::getUsername,liveUser.getUsername());
        LiveUser one = liveUserService.getOne(query);
        if (one != null){
            return Msg.error("登录名被占用!");
        }
        liveUserService.editLiveUser(liveUser);
        return Msg.success("编辑成功");
    }

    /**
     * 编辑查询回显
     */
    @GetMapping("/getUserById")
    public Msg getUserById( LiveUser liveUser){
        LiveUser user = liveUserService.getUser(liveUser.getUserId());
        return Msg.success("查询成功",user);
    }

    /**
     * 删除业主
     * */

    @DeleteMapping("/{userId}")
    public Msg delete(@PathVariable("userId") Long userId){
        QueryWrapper<LiveHouse> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(LiveHouse::getUserId,userId);
        LiveHouse one = liveHouseService.getOne(queryWrapper);
        if (one.getUseStatus().equals("0")){
            return Msg.error("请缴清水电费后退房在删除业主");
        }
        QueryWrapper<LivePark> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(LivePark::getUserId,userId);
        LivePark livePark = liveParkMapper.selectOne(queryWrapper1);
        if (livePark.getLiveStatus().equals("0")){
            return Msg.error("请缴清停车费后退车位在删除业主");
        }
        if (userId != null){
            //删除停车
            QueryWrapper<FeePark> queryPark = new QueryWrapper<>();
            queryPark.lambda().eq(FeePark::getUserId,userId);
            feeParkService.remove(queryPark);
            //删除电费
            QueryWrapper<FeePark> queryPower = new QueryWrapper<>();
            queryPower.lambda().eq(FeePark::getUserId,userId);
            feeParkService.remove(queryPower);
            //删除水费
            QueryWrapper<FeeWater> queryWater = new QueryWrapper<>();
            queryWater.lambda().eq(FeeWater::getUserId,userId);
            feeWaterService.remove(queryWater);
            //删除分配的角色权限
            QueryWrapper<LiveRole> queryLiveRole = new QueryWrapper<>();
            queryLiveRole.lambda().eq(LiveRole::getUserId,userId);
            liveRoleService.remove(queryLiveRole);
            liveHouseService.remove(queryWrapper);
            liveParkMapper.delete(queryWrapper1);
        }
        //删除业主
        boolean b = liveUserService.removeById(userId);
        if (b){
            return Msg.success("删除业主成功!");
        }
        return Msg.error("删除业主失败!");

    }

    /**
     * 分配未使用房屋
     * */
    @PostMapping("/assignSave")
    @PreAuthorize("hasAuthority('sys:liveUser:assignHome')")
    public Msg assignSave(@RequestBody AssignHouseParm parm){
        liveUserService.assignHouse(parm);
        return Msg.success("分配房屋成功!");
    }

    /**
     * 分配未使用的车位
     * */
    @PostMapping("/assignParkSave")
    @PreAuthorize("hasAuthority('sys:liveUser:assignCar')")
    public Msg assignParkSave(@RequestBody LivePark livePark){
        liveUserService.assignPark(livePark);
        return Msg.success("分配车位成功!");
    }

    /**
     * 退房：
     *      1.查询电费、水费是否已经交清；
     *     2.更新租户和房屋关系表状态为解绑；
     *     3.更新房屋表的使用状态为未使用；
     */
    @PostMapping("/returnHouse")
    @PreAuthorize("hasAuthority('sys:liveUser:returnHome')")
    public Msg returnHouse(@RequestBody AssignHouseParm parm){
       //1.查询电费、水费是否已经交清
        //构造条件
        QueryWrapper<FeeWater> queryWater = new QueryWrapper();
        queryWater.lambda().eq(FeeWater::getHouseId,parm.getHouseId()).eq(FeeWater::getUserId,parm.getUserId())
                .eq(FeeWater::getPayWaterStatus,"0");
        List<FeeWater> list = feeWaterService.list(queryWater);
        if (list != null && list.size()>0){
            return Msg.error("请缴水费之后再退房!");
        }
        //查询电费
        QueryWrapper<FeePower> queryPower = new QueryWrapper();
        queryPower.lambda().eq(FeePower::getHouseId,parm.getHouseId()).eq(FeePower::getUserId,parm.getUserId())
        .eq(FeePower::getPayPowerStatus,"0");
        List<FeePower> list1 = feePowerService.list(queryPower);
        if (list1 != null && list1.size()>0){
            return Msg.error("请缴电费之后再退房!");
        }
        //2.更新租户和房屋关系表状态为解绑；
        //3.更新房屋表的使用状态为未使用；
        liveUserService.returnHouse(parm);
        return Msg.success("退房成功");
    }


    /**
     * 退车位
     *      1.查询车位费是否已经交清；
     *     2.更新租户和车位的关系为解绑；
     *     3.更新车位的使用状态为未使用；
     *
     */
    @PostMapping("/returnPark")
    @PreAuthorize("hasAuthority('sys:liveUser:returnCar')")
    public Msg returnPark(@RequestBody LivePark livePark){
        //1.查询车费是否已经交清
        //构造条件
        QueryWrapper<FeePark> queryPark = new QueryWrapper();
        queryPark.lambda().eq(FeePark::getParkId,livePark.getParkId())
                .eq(FeePark::getUserId,livePark.getUserId())
                .eq(FeePark::getPayParkStatus,"0");
        List<FeePark> list = feeParkService.list(queryPark);
        if (list != null && list.size()>0){
            return Msg.error("请缴清停车费后再退车位!");
        }

        //2.更新租户和车位的关系为解绑；
        //3.更新车位的使用状态为未使用；
        liveUserService.returnPark(livePark);
        return Msg.success("退车位成功");
    }
}
